from gm.api import *
import numpy as np
import talib


def init(context):
    context.symbol = 'SHSE.600000'
    context.frequency = '1d'
    context.fields = 'open,high,low,close,volume'
    context.count = 25

    context.k1 = 0.7

    schedule(schedule_func=algo, date_rule='1d', time_rule='09:30:00')
    context.flag = 100
    context.flag_check = 2


def algo(context):
    today = context.now
    last_day = get_previous_trading_date('SZSE', today)

    data = history_n(
        symbol=context.symbol,
        frequency=context.frequency,
        count=context.count,
        end_time=last_day,
        fields=context.fields,
        fill_missing='last',
        adjust=ADJUST_PREV,
        df=True
    )
    high = np.asarray((data['high'].values))
    low = np.asarray((data['low'].values))
    close = np.asarray((data['close'].values))
    open = np.asarray((data['open'].values))

    hh = np.max(high)
    hc = np.max(close)
    lc = np.min(close)
    ll = np.min(low)

    range = np.max([hh - hc, lc - ll])
    data_now = current(symbols=context.symbol)[0]
    print(type(data_now), data_now)
    data_now_open = data_now['open']
    data_now_price = data_now['price']

    range_up_price = data_now_open + context.k1 * range
    if (data_now_price > range_up_price):
        order_target_percent(symbol=context.symbol, percent=0.75, position_side=PositionSide_Long,
                             order_type=OrderType_Market, price=0)
        context.flag = 0
        if (context.flag == context.flag_check):
            order_target_percent(symbol=context.symbol, percent=0, position_side=PositionSide_Long,
                                 order_type=OrderType_Market, price=0)
            context.flag = 100
        context.flag += 1


if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename='程序5_12DualThrust策略.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2017-01-01 09:00:00',
        backtest_end_time='2017-12-31 15:00:00',
        backtest_initial_cash=20000,
        backtest_adjust=ADJUST_PREV,
    )
